package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.AccountLog;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.mapper.AccountLogMapper;
import cn.wolfcode.mapper.AccountTransactionMapper;
import cn.wolfcode.mapper.UsableIntegralMapper;
import cn.wolfcode.service.IUsableIntegralService;
import cn.wolfcode.web.msg.IntergralCodeMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class UsableIntegralServiceImpl implements IUsableIntegralService {
    @Autowired
    private UsableIntegralMapper usableIntegralMapper;
    @Autowired
    private AccountTransactionMapper accountTransactionMapper;
    @Autowired
    private AccountLogMapper accountLogMapper;

    @Override
    @Transactional
    public void decrIntergral(OperateIntergralVo operateIntergralVo) {
        //向t_account_log表中插入数据
        AccountLog accountLog = new AccountLog();
        accountLog.setPkValue(operateIntergralVo.getPk());
        accountLog.setType(AccountLog.TYPE_DECR);
        accountLog.setAmount(operateIntergralVo.getValue());
        accountLog.setGmtTime(new Date());
        accountLog.setInfo(operateIntergralVo.getInfo());
        accountLogMapper.insert(accountLog);
        //减少积分
        int count = usableIntegralMapper.decrIntergral(operateIntergralVo.getValue(), operateIntergralVo.getUserId());
        if (count == 0) {
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_NOT_ENOUGH);
        }
    }

    @Override
    public void incrIntergral(OperateIntergralVo operateIntergralVo) {
        //向t_account_log表中插入数据
        AccountLog accountLog = new AccountLog();
        accountLog.setPkValue(operateIntergralVo.getPk());
        accountLog.setType(AccountLog.TYPE_INCR);
        accountLog.setAmount(operateIntergralVo.getValue());
        accountLog.setGmtTime(new Date());
        accountLog.setInfo(operateIntergralVo.getInfo());
        accountLogMapper.insert(accountLog);
        //增加积分
        usableIntegralMapper.addIntergral(operateIntergralVo.getUserId(), operateIntergralVo.getValue());

    }
}
